package cn.jathlon.io;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * 读、写文件类
 * 1,异常处理
 * @author chen
 *
 */
public class ReaderWriter {

	private final static String CHARTSET = "UTF-8";
	private static BufferedReader br;
	private static PrintWriter pw;
	
	/**
	 * 取读文件实例
	 * @param filePath
	 * @return BufferedReader
	 */
	public static BufferedReader getReaderInstance(String filePath){
		return getReaderInstance(filePath, CHARTSET);
	}
	
	/**
	 * 取读文件实例
	 * @param filePath
	 * @return BufferedReader
	 */
	public static BufferedReader getReaderInstance(String filePath, String charset){
		try {
			br = new BufferedReader(
				new InputStreamReader(new FileInputStream(filePath), charset));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return br;
	}
	
	/**
	 * 取写文件实例
	 * @param filePath
	 * @return BufferedReader
	 */
	public static PrintWriter getWriterInstance(String filePath){
		return getWriterInstance(filePath, false, CHARTSET);
	}
	
	/**
	 * 取写文件实例
	 * @param filePath
	 * @return BufferedReader
	 */
	public static PrintWriter getWriterInstance(String filePath, boolean append ){
		return getWriterInstance(filePath, append, CHARTSET);
	}
	
	/**
	 * 取写文件实例
	 * @param filePath
	 * @return BufferedReader
	 */
	public static PrintWriter getWriterInstance(String filePath, boolean append, String charset){
		try {
			pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(filePath, append), charset));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return pw;
	}
	
	/**
	 * 释放内存
	 */
	public void cleanUp(){
		br = null;
		pw = null;
	}
	
	
}
